package live.hotel.dao.impl;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import live.common.DBHelper;
import live.common.Format;
import live.common.Log4jXmlConfig;
import live.common.Page;
import live.hotel.entity.*;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.Element;

import com.hotel.api.entity.AddBookingResponse;
import com.hotel.api.entity.CheckPaxItem;
import com.hotel.api.entity.ContactPax;
import com.hotel.api.entity.Creditcard;
import com.hotel.api.entity.Error;
import com.hotel.api.services.AddBookingService;
import com.hotel.api.utils.ConstEnum.CONFIRM_METHOD;
import com.hotel.api.utils.ConstEnum.PAYMENTTYPE;

public class OrderMange {
	private String error=null;

	public String getError() {
		return error;
	}

	public void setError(String error) {
		this.error = error;
	}
	Logger LOG = Log4jXmlConfig.getInstance().returnLogger(this.getClass());
	/**
	 * 返回订单号
	 * 
	 * @param item
	 * @return
	 * @throws Exception
	 */
	public Order returnOrder(Order item,Creditcard creditcard) throws Exception {
		String resRsp="";
		CheckPaxItem paxItem = new CheckPaxItem();
		paxItem.setMobile(item.getMobile());
		String[] paxNames=item.getPaxName().split(",");
		paxItem.setPaxNames(paxNames);
		ContactPax pax = new ContactPax();
		String confirmMethod="";
		if(Format.getInstance().isNotNullOrEmpty(item.getMobile())){
			confirmMethod = CONFIRM_METHOD.SMS.toString();
			pax.setMobile(item.getMobile());
			pax.setName(item.getName());
		}
		pax.setConfirmMethod(confirmMethod);
		String paxName ="";
		for (int i = 0; i < paxNames.length; i++) {
			paxName+=paxNames[i];
			if(i!=paxNames.length-1){
				paxName+=",";
			}
		}
		item.setPaxName(paxName);
		AddBookingResponse book = new AddBookingService().addBookingResult(PAYMENTTYPE.T, item.getArrivalTimeFrom(), item.getArrivalTimeTo(), item.getCity(), item.getItem(), item.getRoomNo(), item.getNumberOfRooms(), 0, item.getCheckInDate(), item.getCheckOutDate(), pax, creditcard, null, paxItem);
		if(book.getErrors()==null){
			if(book.getIsSuccess().equals("1")){
			item.setOrderStatus(book.getIsSuccess());
			item.setOrderId(book.getOrderId());
			item.setTotalBalsPrice(book.getTotalBalsAmount());
			item.setTotalSalePrice(book.getTotalSaleAmount());
			item.setTotalCommision(book.getCommissions());
			if(addOrder(item) >= 0){
				Other others = new Other();
				others.setOrderNo(item.getOrderId());
				others.setPaxNames(paxName);
				others.setArrivalTimeFrom(item.getArrivalTimeFrom());
				others.setArrivalTimeTo(item.getArrivalTimeTo());
				others.setCardType(creditcard!=null?creditcard.getCreditCardType():null);
				others.setCardNumber(creditcard!=null?creditcard.getCreditCardNumber():null);
				others.setHoldername(creditcard!=null?creditcard.getCreditCardHolderName():null);
				others.setIdcardtype(creditcard!=null?creditcard.getIdCardType():null);
				others.setIdcardnum(creditcard!=null?creditcard.getIdCardNumber():null);
				others.setCvv(creditcard!=null?creditcard.getCvv():null);
				others.setExpired(creditcard!=null?creditcard.getExpired():null);
				others.setName(pax.getName());
				others.setMobile(pax.getMobile());
				addOther(others);
			}
			}else{
				setError(book.getDescription());
			}
		}else{
			for (Error error : book.getErrors()) {
				resRsp+=error.getErrorCode()+":"+error.getErrorDesc()+";";
			}
			setError(resRsp);
		}
		addResRsp(item, resRsp);
		return item;
	}
	/**
	 * 酒店预订相关信息录入
	 * @param others
	 * @throws SQLException
	 */
	private void addOther(Other others) throws SQLException{
		DBHelper db = DBHelper.getInstance();
		String sql = "{call add_hotel_others(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}";
		Object[] objs = new Object[]{
				others.getOrderNo(),others.getPaxNames(),others.getArrivalTimeFrom(),
				others.getArrivalTimeTo(),others.getAddBed(),others.getBedType(),
				others.getNosmoking(),others.getAddmeal(),others.getRemarks(),
				others.getName(),others.getMobile(),others.getTel(),others.getFax(),
				others.getEmail(),others.getCardType(),others.getCardNumber(),
				others.getCvv(),others.getHoldername(),others.getExpired(),
				others.getIdcardtype(),others.getIdcardnum()
		};
		db.update(sql,objs);
		db.close();
	}
	private void addResRsp(Order item,String resRsp){
		String sql = "{call addNewHotelResRsp(?,?,?,?,?,?,?,?,?,?,?,?)}";
		Object[] objs = new Object[12];
		objs[0]=item.getPaxName();
		objs[1]=item.getCity();
		objs[2]=item.getItem();
		objs[3]=item.getRoomNo();
		objs[4]=item.getCheckInDate();
		objs[5]=item.getCheckOutDate();
		objs[6]=Format.getInstance().isNotNullOrEmpty(item.getOrderId())?item.getOrderId():null;
		objs[7]=item.getHotelName();
		objs[8]=item.getRoomType();
		objs[9]=Format.getInstance().isNotNullOrEmpty(resRsp)?resRsp:null;
		objs[10]=item.getOtherRemark();
		objs[11]="on";
		DBHelper dh =DBHelper.getInstance();
		try {
			dh.update(sql,objs);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			dh.close();
		}
	}

	/**
	 * 佣金总价
	 * 
	 * @param doc
	 * @param nodeName
	 * @return
	 */
	private String returnCommisionTotal(Document doc, String nodeName) {
		List<String> nodes = doc.selectNodes(nodeName);
		Iterator iterator = nodes.iterator();
		double commisionTotal = 0D;
		Element element = null;
		while (iterator.hasNext()) {
			element = (Element) iterator.next();
			commisionTotal += Double.parseDouble(element
					.elementTextTrim("Commision"));
		}
		return commisionTotal + "";
	}

	/**
	 * 新增订单
	 * 
	 * @param item
	 * @throws SQLException
	 */
	private int addOrder(Order item) throws SQLException {
		DBHelper db = DBHelper.getInstance();
		String otherInfos = item.getOtherRemark();
		String sql = "{call add_Hotel_Order(?,?,?,?,?,?,?,?,?,?,?,?)}";
		Object[] objs = new Object[]{
				item.getOrderId(),item.getCheckInDate(),item.getCheckOutDate(),
				item.getOtherRemark(),Format.getInstance().dateFormatString(new Date(), "yyyy-MM-dd HH:mm:ss"),
				item.getTotalSalePrice(),item.getTotalBalsPrice(),item.getTotalCommision(),
				item.getHotelName(),item.getRoomType(),item.getNumberOfRooms(),"on"
		};
		int rowcount = db.update(sql,objs);
		db.close();
		return rowcount;
	}
	

	/**
	 * 查询订单
	 * a
	 * @param storeNo
	 * @return
	 * @throws SQLException
	 */
	public List<Order> queryOrders(String storeNo) throws SQLException {
		DBHelper db = DBHelper.getInstance();
		Order item = null;
		List results = new ArrayList();
		List<Map> orderList = db
				.queryRecordsMap("SELECT * FROM Hotel_Order where storeNo='"
						+ storeNo + "' order by placeTime desc");
		for (Map map : orderList) {
			item = new Order();
			item.setOrderId(map.get("orderNo").toString());
			item.setTotalSalePrice(map.get("totalSalePrice").toString());
			item.setCheckInDate(map.get("placeTime").toString());
			item.setOrderStatus(map.get("status").toString());
			item.setName(map.get("memberNum").toString());
			results.add(item);
		}
		db.close();
		return results;
	}

	/***************************************************************************
	 * 查询分页
	 * 
	 * @throws SQLException
	 */

	@SuppressWarnings("unchecked")
	public List<Order> queryOrders_fy(String storeNo, Page page)
			throws SQLException {
		DBHelper db = DBHelper.getInstance();
		Order item = null;
		List results = new ArrayList();
		String sql = "{call pro_Common_PageView(?,?,?,?)}";
		String execSql = "SELECT * FROM Hotel_Order WHERE 1=1 AND storeNo='"
				+ storeNo + "' order by placeTime desc ";
		Object[] args = new Object[4];
		args[0] = execSql;
		args[1] = page.getPageIndex();
		args[2] = page.getPageSize();
		args[3] = "";
		List<Map> orderList = db.queryRecordsMap(sql, args);
		for (Map map : orderList) {
			item = new Order();
			item.setOrderId(map.get("orderNo").toString());
			item.setTotalSalePrice(map.get("totalSalePrice").toString());
			item.setCheckInDate(map.get("placeTime").toString());
			item.setOrderStatus(map.get("status").toString());
			item.setName(map.get("memberNum").toString());
			item.setHotelName(map.get("hotelName").toString());
			item.setRoomType(map.get("roomType").toString());
			item.setNumberOfRooms(Integer
					.valueOf(map.get("roomNum").toString()));
			results.add(item);
		}
		page.setRecordCount(db.returnOutParam(execSql, args));
		db.close();
		return results;
	}

	public List queryOrders(String storeNo, Page page) throws SQLException {
		DBHelper db = DBHelper.getInstance();
		String execSql = "{call pro_Common_PageView(?,?,?,?)}";
		StringBuffer sql = new StringBuffer(
				"SELECT * FROM Hotel_Order WHERE 1=1 AND storeNo='" + storeNo
						+ "'  order by placeTime desc");
		Object[] args = new Object[4];
		args[0] = sql.toString();
		args[1] = page.getPageIndex();
		args[2] = page.getPageSize();
		args[3] = "";
		Order item = null;
		List orders = new ArrayList();
		List<Map> list = db.queryRecordsMap(execSql, args);
		int count=0;
		for (Map map : list) {
			item = new Order();
			item.setOrderId(map.get("orderNo").toString());
			item.setTotalSalePrice(map.get("totalSalePrice")!=null?map.get("totalSalePrice").toString():"0");
			item.setCheckInDate(map.get("inDate").toString());
			item.setCheckOutDate(map.get("outDate").toString());
			item.setOrderStatus(map.get("status").toString());
			item.setHotelName(Format.getInstance().isNotNullOrEmpty(map.get("hotelName"))?map.get("hotelName").toString():"———");
			item.setRoomType(Format.getInstance().isNotNullOrEmpty(map.get("roomType"))?map.get("roomType").toString():"———");
			item.setNumberOfRooms(Integer
					.parseInt(map.get("roomNum")!=null?map.get("roomNum").toString():"1"));
			orders.add(item);
			count++;
		}
		page.setRecordCount(db.returnOutParam(execSql, args));
		db.close();
		return orders;
	}

	@SuppressWarnings("unchecked")
	public int mobbile_sum(String storeNo) throws SQLException {
		DBHelper db = DBHelper.getInstance();
		StringBuffer sql = new StringBuffer(
				"select count(*) as sumcount FROM Hotel_Order  where  storeNo='"
						+ storeNo + "'");
		List<Map> lsitmap = db.queryRecordsMap(sql.toString());
		db.close();
		for (Map map : lsitmap) {
			return Integer.valueOf(map.get("sumcount").toString());
		}
		return 0;
	}

	
}
